/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import ohos.utils.FileWatcher;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import io.sentry.IEnvelopeSender;
import io.sentry.ILogger;
import io.sentry.hints.ApplyScopeData;
import io.sentry.hints.Cached;
import io.sentry.hints.Flushable;
import io.sentry.hints.Resettable;
import io.sentry.hints.Retryable;
import io.sentry.hints.SubmissionResult;
import io.sentry.util.Objects;

import static io.sentry.SentryLevel.ERROR;

/**
 * EnvelopeFileObserver
 *
 * @since 2021-06-01
 */

public final class EnvelopeFileObserver extends FileWatcher implements FileWatcher.EventHandler {
    private final IEnvelopeSender envelopeSender;
    private @NotNull
    final ILogger logger;
    private final long flushTimeoutMillis;
    private String path = null;

    // The preferred overload (Taking File instead of String) is only available from API 29
    @SuppressWarnings("deprecation")
    public EnvelopeFileObserver(
        Path path,
        IEnvelopeSender envelopeSender,
        @NotNull ILogger logger,
        final long flushTimeoutMillis) {
        this.envelopeSender = Objects.requireNonNull(envelopeSender, "Envelope sender is required.");
        this.logger = Objects.requireNonNull(logger, "Logger is required.");
        this.flushTimeoutMillis = flushTimeoutMillis;
        try {
            this.path = path.toFile().getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        addWatch(path, this, false, null);
    }

    @Override
    public void onEvent(WatchEvent<?> watchEvent) {
        final CachedEnvelopeHint hint = new CachedEnvelopeHint(flushTimeoutMillis, logger);
        envelopeSender.processEnvelopeFile(path, hint);
    }

    private static final class CachedEnvelopeHint
        implements Cached, Retryable, SubmissionResult, Flushable, ApplyScopeData, Resettable {
        boolean isRetry;
        boolean isSucceeded;

        private @NotNull CountDownLatch latch;
        private final long flushTimeoutMillis;
        private final @NotNull ILogger logger;

        public CachedEnvelopeHint(final long flushTimeoutMillis, final @NotNull ILogger logger) {
            reset();
            this.flushTimeoutMillis = flushTimeoutMillis;
            this.logger = Objects.requireNonNull(logger, "ILogger is required.");
        }

        @Override
        public boolean waitFlush() {
            try {
                return latch.await(flushTimeoutMillis, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.log(ERROR, "Exception while awaiting on lock.", e);
            }
            return false;
        }

        @Override
        public boolean isRetry() {
            return isRetry;
        }

        @Override
        public void setRetry(boolean retry) {
            this.isRetry = retry;
        }

        @Override
        public void setResult(boolean succeeded) {
            this.isSucceeded = succeeded;
            latch.countDown();
        }

        @Override
        public boolean isSuccess() {
            return isSucceeded;
        }

        @Override
        public void reset() {
            latch = new CountDownLatch(1);
            isRetry = false;
            isSucceeded = false;
        }
    }
}
